package com.mocha.bss.excel;

import com.coffee.attachment.ExcelDocumentDTO;
import com.coffee.attachment.NotifyExcelDownloadDTO;
import com.coffee.attachment.excel.ExcelHandler;
import com.coffee.attachment.service.MochaAttachmentService;
import com.coffee.attachment.service.MochaExcelService;
import com.coffee.core.JSONUtils;
import com.coffee.excel.MochaExcelSheet;
import com.coffee.ws.CoffeeSessionManager;
import com.coffee.ws.CoffeeWebsocketResponse;
import com.mocha.bss.websocket.message.DocDownloadPushMessage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author songkui
 * @since 2024/4/19 18:05
 */
@Slf4j
@AllArgsConstructor
@Component("excelHandler")
public class BssExcelHandler implements ExcelHandler {

    //TODO excel file 配置信息 就在此 服务中 因此可以直接调用 service 否则需要走 feign 接口调用
    private final MochaExcelService mochaExcelService;
    private final MochaAttachmentService mochaAttachmentService;
    private final AttachmentConverter attachmentConverter;
//    private final MochaMQTemplate mochaMQTemplate;


    @Override
    public MochaExcelSheet findExcelSheetByCodeFile(String excelCode, String fields) {
        return mochaExcelService.findExcelField(excelCode, fields);
    }

    @Override
    public Long saveExcelDocument(ExcelDocumentDTO excelDocumentDTO) {
        return mochaAttachmentService.saveDocument(attachmentConverter.toAttachDocumentEntity(excelDocumentDTO));
    }

    //TODO 如果 websocket 没有在该服务器 ，则需要通过MQ 关播
    @Override
    public void notifyExcelDownload(NotifyExcelDownloadDTO dto) {

        if (null == dto || null == dto.getUserId()){
            log.error("Notify excel download data is null");
            return;
        }

        if (null == CoffeeSessionManager.getSession(dto.getUserId())){
            //TODO 如果websocket链接 部署了多台; 如果只有一台 可以不处理；
//            ExcelDownloadMQMessage message = new ExcelDownloadMQMessage();
//            message.setKey(StrUtil.uuid());
//            message.setPayload(dto);
//            mochaMQTemplate.syncSend(ExcelDownloadMQConstant.COFFEE_BROADCAST_WEB_TOPIC, ExcelDownloadMQConstant.COFFEE_BROADCAST_WEB_EXCEL_TAG, message);
        }else {
            //TODO 如果 该用户websocket链接没有在 该服务器 需要广播给其他服务器
            DocDownloadPushMessage docDownloadPushMessage = DocDownloadPushMessage.builder().docId(dto.getDocId()).docTitle(dto.getDocTitle()).exceptionInfo(dto.getExceptionInfo()).build();
            CoffeeSessionManager.sendText(dto.getUserId(), JSONUtils.toJson(CoffeeWebsocketResponse.responseSuccess(docDownloadPushMessage)));
        }

    }
}
